package com.dotto.atos.services.actions;

import android.os.AsyncTask;

import com.dotto.atos.Config;
import com.dotto.atos.models.User;
import com.dotto.atos.services.errors.UserServiceError;
import com.dotto.atos.services.listeners.IUserServiceListener;

public class UserService {

	private static UserServiceLoginTask loginTask;

	public static void login(String branchCode, String userCode,
			String password, IUserServiceListener listener) {
		if (loginTask == null) {
			loginTask = new UserServiceLoginTask();
			loginTask.setParameters(branchCode, userCode, password, listener);
			loginTask.execute();
		}
	}

	private static class UserServiceLoginTask extends
			AsyncTask<Void, Void, Boolean> {

		private String branchCode;
		private String userCode;
		private String password;
		private IUserServiceListener listener;

		public void setParameters(String branchCode, String userCode,
				String password, IUserServiceListener listener) {
			this.branchCode = branchCode;
			this.userCode = userCode;
			this.password = password;
			this.listener = listener;
		}

		@Override
		protected Boolean doInBackground(Void... voids) {
			// TODO : check server for demo check config
			if (userCode.equals(Config.DEMO_USER)
					&& password.equals(Config.DEMO_PASSWORD)) {
				User user = new User();
				user.setId(1L);
				user.setBranchCode(branchCode);
				user.setPassword(password);
				user.setUserCode(userCode);
				if (listener != null)
					listener.onUserServiceResponse(user);
			} else {
				if (listener != null)
					listener.onUserServiceError(new UserServiceError(
							UserServiceError.USER_NAME_CODE_WRONG));
			}
			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			loginTask = null;
		}
	}

}
